#!/usr/bin/python3

import os
import re
import subprocess
import sys

if __name__ == "__main__":
    FEDORA_VERSION="36"

    #WORK_DIR=sys.argv[1]
    WORK_DIR=subprocess.run(["pwd"],stdout=subprocess.PIPE,encoding="utf-8").stdout
    WORK_DIR=WORK_DIR[0:len(WORK_DIR)-len("autotools")]
    WORK_DIR=WORK_DIR[0:len(WORK_DIR)-1]+"/"
    
    print("work direction is:"+WORK_DIR)
    print("input the first character;eg:b")
    Firstcode= input()
    

    print("FEDORA_VERSION:"+FEDORA_VERSION+"\n")

    FILE_NAME="index.html"
    WGET_DIR="https://mirrors.163.com/fedora/releases/"+FEDORA_VERSION+"/Everything/source/tree/Packages/"
    #arg0=firstcode of pkg

    #Download index.html()
    indexurl=WGET_DIR+Firstcode+"/"
    subprocess.run(["rm","./"+Firstcode+"/"+FILE_NAME])
    subprocess.run(["wget","-P./"+Firstcode,indexurl])
    #subprocess.run(["mkdir",Firstcode])

    #Get src.rpm's name 
    htmlfile=open("./"+Firstcode+"/"+FILE_NAME,'r')
    pkgname_str=[]
    result=[]
    pkgname="1"

    htmllines=htmlfile.readlines()
    #print(line)
    for line in htmllines :
        for i in range(len(line)) :
            if line[i:i+7]=="src.rpm" :
                for j in range(len(line)) :
                    if line[j-5:j] == "href=" :
                        pkgname_str.append(line[j+1:i+7])
                        #print(line[j+1:i+7])
                        break
                break

    #pkgname_str=<name>.fcxx.src.rpm
    htmlfile.close()
    #for every src.rpm           
    succeededpkg=0
    for srcname in pkgname_str:
        return_code  = subprocess.run(["wget","-P./"+Firstcode,WGET_DIR+Firstcode+"/"+srcname])
        if return_code.returncode==0 :
            result.append("succeeded")
            for j in range(len(srcname)):

                #判断防止没有.fcxx的情况下长度溢出
                if j<=len(srcname)-6:
                    if srcname[j:j+len(".fc"+FEDORA_VERSION)]==".fc"+FEDORA_VERSION:
                        pkgname=srcname[0:j]
                        break

            succeededpkg=succeededpkg+1
            print(Firstcode,pkgname,srcname)




            subprocess.run(["sh","makedir.sh",Firstcode,pkgname,srcname])
        else :
            result.append("downloadFail")
    #pkgname=<name>

    #open时创建文件，一定要绝对路径
    resultfile=open(WORK_DIR+Firstcode+"/Result",'w')
    for i in range(len(pkgname_str)):
        resultfile.write(pkgname_str[i]+(70-len(pkgname_str[i]))*" "+result[i]+"\n")
    resultfile.close()
    print("------------------------------------Tast Over--------------------------------------")
    print("Packages number:"+str(len(pkgname_str))+"  Download Succeeded number:"+str(succeededpkg)+"\n")
    subprocess.run(["cat","./"+Firstcode+"/Result"]) 
    print('\n')
                




